#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import time,uuid

from datetime import datetime
from day3_orm import Model,StringField,BooleanField,FloatField,TextField

def next_id():
	return '%015d%s000' % (int(time.time()*1000),uuid.uuid4().hex)

class User(Model):
	"""docstring for User"""
	__table__ = 'users';
	id = StringField(primary_key=True,default=next_id,ddl='varchar(5)')
	email = StringField(ddl='varchar(50)')
	passwd = StringField(ddl='varchar(50)')
	admin = BooleanField();
	name = StringField('varchar(50)')
	image = StringField('varchar(500)') #头先路径
	created_at = FloatField(default=time.time()) #创建时间

#博客文章表		
class Blog(Model):
	"""docstring for Blog"""
	__table__ = 'blogs'

	id = StringField(primary_key=True,default=next_id,ddl='varchar(50)')
	user_id = StringField(ddl='varchar(50)')
	user_name = StringField(ddl='varchar(50)')
	user_image = StringField(ddl='varchar(500)')
	name = StringField(ddl='varchar(50)') #文章标题
	summary = StringField(ddl='varchar(500)') #文章摘要
	content = StringField(ddl='varchar(500)') #文章内容
	created_at=FloatField(default=time.time())

#文章评论表 
class Comment(Model):
	"""docstring for comment"""
	__table__ = 'comments'
		
	id = StringField(primary_key=True,default=next_id,ddl='varchar(50)')
	blog_id = StringField(ddl='varchar(50)')
	user_id = StringField(ddl='varchar(50)')
	user_name = StringField(ddl='varchar(50)')
	user_image = StringField(ddl='varchar(50)')
	content = TextField()
	created_at = FloatField(default=time.time())

'''
#测试数据库代码

import day3_orm
import asyncio
import sys
import random
import math
orm = day3_orm;

#awesome
@asyncio.coroutine
def test_db(loop):
	yield from orm.create_pool(loop,user='root',password='root',db='awesome')	
	email = 'my'+str(random.randint(100,10000))+'@py.com'
	u = User(name='kfz'+str(random.randint(0,100)),email=email,passwd='789321',image='about:blank') #实例化一个User对象就是插入一条数据
	yield from u.save()

for i in range(10):
	r = random.random()
	t = math.floor(r*3)
	num = 1+ t
	print(r,t,num)

loop1 = asyncio.get_event_loop()
loop1.run_until_complete(test_db(loop1))
loop1.close()
#如果异步已经关闭则退出程序,否则会报错(RuntimeError: Event loop is closed),因为会再次执行该代码
if loop1.is_closed():
	sys.exit(0)

'''